package com.fr.function;

import java.util.List;
import com.fr.third.apache.log4j.Logger;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant; 

/**   
 * @ClassName:  DOCWriter   
 * @Description:TODO jacob操作word工具类  
 * @author:  haven 
 * @date:   2018年10月31日 上午12:04:26   
 *     
 * @Copyright: 2018 www.fanruan.com Inc. All rights reserved.  
 */

public class DOCWriter {

	
	/**
	 * word文档
	 * 
	 * 在本类中有两种方式可以进行文档的创建,<br>
	 * 第一种调用 createNewDocument 第二种调用 openDocument
	 */
	public static Logger logger1 = Logger.getLogger(DOCWriter.class);
	/** 日志记录器 */
	private Dispatch document = null;

	/** word运行程序对象 */
	private ActiveXComponent word = null;

	/** 所有word文档 */
	private Dispatch documents = null;

	/**
	 * Selection 对象 代表窗口或窗格中的当前所选内容。 所选内容代表文档中选定（或突出
	 * 
	 * 显示）的区域，如果文档中没有选定任何内容，则代表插入点。 每个文档窗格只能有一个Selection 对象，并且在整个应用程序中只能有一个活动的
	 * 
	 * Selection 对象。
	 */
	private Dispatch selection = null;

	/**
	 * 
	 * Range 对象 代表文档中的一个连续区域。 每个 Range 对象由一个起始字符位置和一个
	 * 
	 * 终止字符位置定义。 说明：与书签在文档中的使用方法类似，Range 对象在 Visual Basic 过程中用来标识文
	 * 
	 * 档的特定部分。 但与书签不同的是，Range对象只在定义该对象的过程运行时才存在。
	 * Range对象独立于所选内容。也就是说，您可以定义和处理一个范围而无需更改所选内
	 * 
	 * 容。还可以在文档中定义多个范围，但每个窗格中只能有一个所选内容。
	 */
	private Dispatch range = null;

	/**
	 * PageSetup 对象 该对象包含文档的所有页面设置属性（如左边距、下边距和纸张大小）
	 * 
	 * 。
	 */
	private Dispatch pageSetup = null;

	/** 文档中的所有表格对象 */
	private Dispatch tables = null;

	/** 一个表格对象 */
	private Dispatch table = null;

	/** 表格所有行对象 */
	private Dispatch rows = null;

	/** 表格所有列对象 */
	private Dispatch cols = null;

	/** 表格指定行对象 */
	private Dispatch row = null;

	/** 表格指定列对象 */
	private Dispatch col = null;

	/** 表格中指定的单元格 */
	private Dispatch cell = null;

	/** 字体 */
	private Dispatch font = null;

	/** 对齐方式 */
	private Dispatch alignment = null;
	/** 当前活动窗口 */
	private Dispatch activeWindow = null;

	/**
	 * 构造方法
	 */
	public DOCWriter() {

		if (this.word == null) {
			/* 初始化应用所要用到的对象实例 */
			this.word = new ActiveXComponent("Word.Application");
			/* 设置Word文档是否可见，true-可见false-不可见 */
			this.word.setProperty("Visible", new Variant(false));
			/* 禁用宏 */
			this.word.setProperty("AutomationSecurity", new Variant(3));
		}
		if (this.documents == null) {
			this.documents = word.getProperty("Documents").toDispatch();

		}
	}

	/**
	 * 设置页面方向和页边距
	 * 
	 * @param orientation
	 *            可取值0或1，分别代表横向和纵向
	 * @param leftMargin
	 *            左边距的值
	 * @param rightMargin
	 *            右边距的值
	 * @param topMargin
	 *            上边距的值
	 * @param buttomMargin
	 *            下边距的值
	 * @param footerDistance
	 *            页脚到页面底端的距离
	 * @param HeaderDistance
	 *            页眉到页面顶端的距离
	 */
	public void setPageSetup(int orientation, int leftMargin, int rightMargin, int topMargin, int

	buttomMargin, int footerDistance, int headerDistance) {

		logger1.info("*****设置页面方向和页边距*****");
		if (this.pageSetup == null) {
			this.getPageSetup();
		}
		Dispatch.put(pageSetup, "Orientation", orientation);
		Dispatch.put(pageSetup, "LeftMargin", leftMargin);
		Dispatch.put(pageSetup, "RightMargin", rightMargin);
		Dispatch.put(pageSetup, "TopMargin", topMargin);
		Dispatch.put(pageSetup, "BottomMargin", buttomMargin);
		Dispatch.put(pageSetup, "FooterDistance", footerDistance);
		Dispatch.put(pageSetup, "HeaderDistance", headerDistance);
		Dispatch.put(pageSetup, "Gutter", 0);
		Dispatch.put(pageSetup, "MirrorMargins", false);
	}

	/**
	 * 打开文件
	 * 
	 * @param inputDoc
	 *            要打开的文件，全路径
	 * @return Dispatch 打开的文件
	 */
	public Dispatch openDocument(String inputDoc) {

		logger1.info("*****打开Word文档*****");
		this.document = Dispatch.call(documents, "Open", inputDoc).toDispatch();
		/* 设置Word文档是否可见，true-可见false-不可见 */
		this.word.setProperty("Visible", new Variant(false));
		this.getSelection();
		this.getRange();
		this.getAlignment();
		this.getFont();
		this.getPageSetup();
		return this.document;
	}

	/**
	 * 创建新的文件
	 * 
	 * @return Dispache 返回新建文件
	 */
	public Dispatch createNewDocument() {

		logger1.info("创建新的文件...");
		this.document = Dispatch.call(documents, "Add").toDispatch();
		this.getSelection();
		this.getRange();
		this.getPageSetup();
		this.getAlignment();
		this.getFont();
		return this.document;
	}

	/**
	 * 选定内容
	 * 
	 * @return Dispatch 选定的范围或插入点
	 */
	public Dispatch getSelection() {

		logger1.info("*****获取选定范围的插入点*****");
		this.selection = word.getProperty("Selection").toDispatch();
		return this.selection;
	}

	/**
	 * 获取当前Document内可以修改的部分
	 * <p>
	 * <br>
	 * 前提条件：选定内容必须存在
	 * 
	 * @param selectedContent
	 *            选定区域
	 * @return 可修改的对象
	 */
	public Dispatch getRange() {

		logger1.info("*****获取当前Document内可以修改的部分*****");
		this.range = Dispatch.get(this.selection, "Range").toDispatch();
		return this.range;
	}

	/**
	 * 获得当前文档的文档页面属性
	 */
	public Dispatch getPageSetup() {

		logger1.info("*****获得当前文档的文档页面属性*****");
		if (this.document == null) {
			logger1.info("*****document对象为空*****");
			return this.pageSetup;
		}
		this.pageSetup = Dispatch.get(this.document, "PageSetup").toDispatch();
		return this.pageSetup;
	}

	/** 取得活动窗体对象 */
	public void getActiveWindow() {
		activeWindow = word.getProperty("ActiveWindow").toDispatch();// 取得活动窗体对象
	}

	/**
	 * 把选定内容或插入点向上移动
	 * 
	 * @param count
	 *            移动的距离
	 */
	public void moveUp(int count) {

		logger1.info("*****把选定内容或插入点向上移动*****");
		for (int i = 0; i < count; i++) {
			Dispatch.call(this.selection, "MoveUp");
		}
	}

	/**
	 * 把选定内容或插入点向下移动
	 * 
	 * @param count
	 *            移动的距离
	 */
	public void moveDown(int count) {

		logger1.info("*****把选定内容或插入点向下移动*****");
		for (int i = 0; i < count; i++) {
			Dispatch.call(this.selection, "MoveDown");
		}
	}

	/**
	 * 把选定内容或插入点向左移动
	 * 
	 * @param count
	 *            移动的距离
	 */
	public void moveLeft(int count) {

		logger1.info("*****把选定内容或插入点向左移动*****");
		for (int i = 0; i < count; i++) {
			Dispatch.call(this.selection, "MoveLeft");
		}
	}

	/**
	 * 把选定内容或插入点向右移动
	 * 
	 * @param count
	 *            移动的距离
	 */
	public void moveRight(int count) {

		logger1.info("*****把选定内容或插入点向右移动*****");
		for (int i = 0; i < count; i++) {
			Dispatch.call(this.selection, "MoveRight");
		}
	}

	/**
	 * 回车键
	 */
	public void enterDown(int count) {

		logger1.info("*****按回车键*****");
		for (int i = 0; i < count; i++) {
			Dispatch.call(this.selection, "TypeParagraph");
		}
	}

	/**
	 * 把插入点移动到文件首位置
	 */
	public void moveStart() {

		logger1.info("*****把插入点移动到文件首位置*****");
		Dispatch.call(this.selection, "HomeKey", new Variant(6));
	}

	public void moveEnd() {

		logger1.info("*****把插入点移动到文件尾位置*****");
		Dispatch.call(this.selection, "EndKey", new Variant(6));
	}

	/**
	 * 从选定内容或插入点开始查找文本
	 * 
	 * @param selection
	 *            选定内容
	 * @param toFindText
	 *            要查找的文本
	 * @return boolean true-查找到并选中该文本，false-未查找到文本
	 */
	public boolean find(String toFindText) {

		logger1.info("*****从选定内容或插入点开始查找文本" + " 要查找内容：  " + toFindText + "*****");
		/* 从selection所在位置开始查询 */
		Dispatch find = Dispatch.call(this.selection, "Find").toDispatch();
		/* 设置要查找的内容 */
		Dispatch.put(find, "Text", toFindText);
		/* 向前查找 */
		Dispatch.put(find, "Forward", "True");
		/* 设置格式 */
		Dispatch.put(find, "Format", "True");
		/* 大小写匹配 */
		Dispatch.put(find, "MatchCase", "True");
		/* 全字匹配 */
		Dispatch.put(find, "MatchWholeWord", "True");
		/* 查找并选中 */
		return Dispatch.call(find, "Execute").getBoolean();
	}

	/**
	 * 把选定内容替换为设定文本
	 * 
	 * @param selection
	 *            选定内容
	 * @param newText
	 *            替换为文本
	 */
	public void replace(String newText) {

		logger1.info("*****把选定内容替换为设定文本*****");
		/* 设置替换文本 */
		Dispatch.put(this.selection, "Text", newText);
	}

	/**
	 * 把选定内容替换为设定文本
	 * 
	 * @param selection
	 *            选定内容
	 * @param newText
	 *            替换为文本
	 */
	public void insertText(String newText) {

		logger1.info("*****插入文本*****");
		/* 设置替换文本 */
		Dispatch wordContent = Dispatch.get(document, "Content").toDispatch();
		Dispatch.call(wordContent, "InsertBefore", newText);
	}

	/**
	 * 将指定的内容替换成图片
	 * 
	 * @param replaceText
	 *            指定的内容
	 * @param imgPath
	 *            图片路径
	 */
	public void replaceTextToImage(String replaceText, String imgPath) {
		moveStart();
		while (find(replaceText)) {
			insertContentImage(imgPath);
			moveEnd();
			// enterDown(1);
		}
	}

	/**
	 * 向当前插入点替换图片
	 *
	 * @param imagePath
	 *            图片的路径
	 */
	public void insertContentImage(String imagePath) {
		Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath);
	}

	/**
	 * 全局替换
	 * 
	 * @param selection
	 *            选定内容或起始插入点
	 * @param oldText
	 *            要替换的文本
	 * @param replaceObj
	 *            替换为文本
	 */
	public void replaceAll(String oldText, Object replaceObj) {

		logger1.info("*****全局替换*****");
		/* 移动到文件开头 */
		moveStart();
		/* 表格替换方式 */
		String newText = (String) replaceObj;
		/* 图片替换方式 */
		if (oldText.indexOf("image") != -1 || newText.lastIndexOf(".bmp") != -1 ||

				newText.lastIndexOf(".jpg") != -1 || newText.lastIndexOf(".gif") != -1) {
			while (find(oldText)) {
				insertImage(newText);
				Dispatch.call(this.selection, "MoveRight");
			}
			/* 正常替换方式 */
		} else {
			while (find(oldText)) {
				replace(newText);
				Dispatch.call(this.selection, "MoveRight");
			}
		}
	}

	/**
	 * 插入图片
	 * 
	 * @param selection
	 *            图片的插入点
	 * @param imagePath
	 *            图片文件（全路径）
	 */
	public void insertImage(String imagePath) {
		Dispatch selection = word.getProperty("Selection").toDispatch();
		Dispatch picture = Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath)
				.toDispatch();
		// 选中图片
		Dispatch.call(picture, "Select"); 
		// 图片的宽度
		Dispatch.put(picture, "Width", new Variant(596)); 
		// 图片的高度
		Dispatch.put(picture, "Height", new Variant(200)); 
		// 取得图片区域
		Dispatch ShapeRange = Dispatch.call(picture, "ConvertToShape").toDispatch(); 
		// 取得图片的格式对象
		Dispatch WrapFormat = Dispatch.get(ShapeRange, "WrapFormat").toDispatch(); 
		//设置图片环绕方式为衬于文字下方
		Dispatch.put(WrapFormat, "Type", 5);
		Dispatch shapeRange = Dispatch.get(selection, "ShapeRange").toDispatch();
		//设置图片距离页面左边的距离
		Dispatch.put(shapeRange, "Left", new Variant(-20));
		//设置图片距离页面右边的距离
		Dispatch.put(shapeRange, "Top", new Variant(-80));

		logger1.info("*****插入首页图片*****");
	}

	/**   
	 * @Title: insertTextBox   
	 * @Description: TODO 插入艺术字作为首页报告周期频率,从网上找的方法,里面应该有很多冗余代码,有能力的可以自行优化以提高性能  
	 * @param: @param str      
	 * @return: void      
	 * @throws   
	 */
	public void insertTextBox(String str) {
		Dispatch shapes = Dispatch.get(document, "Shapes").toDispatch();
		Dispatch AddText = Dispatch.call(shapes, "AddTextEffect", new Variant(0), str, "华文楷体", new Variant(60),
				new Variant(true), new Variant(false), new Variant(0), new Variant(60)).toDispatch();
		Dispatch.call(AddText, "Select"); // 选中图片
		Dispatch shapeRange = Dispatch.get(selection, "ShapeRange").toDispatch();
		Dispatch.put(shapeRange, "Name", "PowerPlusWaterMarkObject6");
		Dispatch textEffect = Dispatch.get(shapeRange, "TextEffect").toDispatch();
		Dispatch.put(textEffect, "NormalizedHeight", new Boolean(false));
		Dispatch line = Dispatch.get(shapeRange, "Line").toDispatch();
		Dispatch.put(line, "Visible", new Boolean(false));
		Dispatch fill = Dispatch.get(shapeRange, "Fill").toDispatch();
		Dispatch.put(fill, "Visible", new Boolean(true));
		Dispatch.put(fill, "Transparency", new Variant(0));// 设置水印透明度
		Dispatch foreColor = Dispatch.get(fill, "ForeColor").toDispatch();
		Dispatch.put(foreColor, "RGB", new Variant(16777215));// 设置水印颜色
		Dispatch.call(fill, "Solid");
		Dispatch.put(shapeRange, "Rotation", new Variant(0));// 旋转角度
		Dispatch.put(shapeRange, "LockAspectRatio", new Boolean(true));// 调整大小时保持其长宽比例不变
		Dispatch.put(shapeRange, "Height", new Variant(10));// 高
		Dispatch.put(shapeRange, "Width", new Variant(120));// 宽
		Dispatch.put(shapeRange, "Left", new Variant(0));//距离页面左端
		Dispatch.put(shapeRange, "Top", new Variant(-35));//距离页面上方

		logger1.info("*****插入首页报告周期频率*****");
	}

	/**   
	 * @Title: insertImageLast   
	 * @Description: TODO 插入图片作为文档末尾重要声明  
	 * @param: @param imagePath 图片路径     
	 * @return: void      
	 * @throws   
	 */
	
	public void insertImageLast(String imagePath) {
		Dispatch selection = word.getProperty("Selection").toDispatch();
		Dispatch picture = Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath)
				.toDispatch();
		Dispatch.call(picture, "Select"); // 选中图片
		Dispatch.put(picture, "Width", new Variant(500)); // 图片的宽度
		Dispatch.put(picture, "Height", new Variant(120)); // 图片的高度
		Dispatch ShapeRange = Dispatch.call(picture, "ConvertToShape").toDispatch(); // 取得图片区域
		Dispatch WrapFormat = Dispatch.get(ShapeRange, "WrapFormat").toDispatch(); // 取得图片的格式对象
		Dispatch.put(WrapFormat, "Type", 0);
		Dispatch shapeRange = Dispatch.get(selection, "ShapeRange").toDispatch();
		Dispatch.put(shapeRange, "Left", new Variant(50));
		Dispatch.put(shapeRange, "Top", new Variant(660));
		logger1.info("*****插入重要声明*****");
		logger1.info("*****插入重要声明*****");
	}

	/**   
	 * @Title: adjImage   
	 * @Description: TODO 将文档中插入的图片调整为嵌入式环绕方式 
	 * @param:       
	 * @return: void      
	 * @throws   
	 */
	public void adjImage() {
		Dispatch picturenum = Dispatch.get(document, "InLineShapes").toDispatch();
		// 获取图片数量
		int a = Dispatch.get(picturenum, "Count").getInt();
		for (int i = a; i > 0; i = i - 1) {
			Dispatch pictures = Dispatch.get(document, "InLineShapes").toDispatch();
			Dispatch picture = Dispatch.call(pictures, "Item", new Variant(i)).toDispatch();
			// 选中图片
			Dispatch.call(picture, "Select"); 
			//设置图片高度和宽度
			// Dispatch.put(picture, "Width", new Variant(496)); // 图片的宽度
			// Dispatch.put(picture, "Height", new Variant(210)); // 图片的高度
			// 取得图片区域
			Dispatch ShapeRange = Dispatch.call(picture, "ConvertToShape").toDispatch(); 
			// 取得图片的格式对象
			Dispatch WrapFormat = Dispatch.get(ShapeRange, "WrapFormat").toDispatch(); 
			//设置图片环绕方式为嵌入式
			Dispatch.put(WrapFormat, "Type", 1);
			Dispatch shapeRange = Dispatch.get(selection, "ShapeRange").toDispatch();
			//设置图片距离页面左边和顶端的距离
			Dispatch.put(shapeRange, "Left", new Variant(20));
			Dispatch.put(shapeRange, "Top", new Variant(0));

			logger1.info("*****调整第" + i + "张图片*****");
		}
	}

	/**
	 * 插入图片
	 * 
	 * @param pages
	 *            总页数
	 * @param imgPath
	 *            图片路径
	 * @param left
	 *            距离左上角位置
	 * @param top
	 *            距离上角位置
	 */
	public void setImages(int pages, String imgPath, int left, int top) {
		for (int i = 0; i < pages; i++) {
			Dispatch selection = Dispatch.get(word, "Selection").toDispatch();
			Dispatch inLineShapes = Dispatch.get(selection, "InLineShapes").toDispatch();
			Dispatch picture = Dispatch.call(inLineShapes, "AddPicture", imgPath).toDispatch();
			// 选中图片
			Dispatch.call(picture, "Select");
			// 设置宽度高度
			Dispatch.put(picture, "Width", new Variant(100));
			Dispatch.put(picture, "Height", new Variant(100));
			// 设置图片相对左上角偏移位置
			selection = Dispatch.get(word, "Selection").toDispatch();
			Dispatch shapeRange = Dispatch.get(selection, "ShapeRange").toDispatch();
			Dispatch.put(shapeRange, "Left", new Variant(left));
			Dispatch.put(shapeRange, "Top", new Variant(top));

			// 翻到下一页
			Dispatch browser = Dispatch.get(word, "Browser").toDispatch();
			Dispatch.call(browser, "Next");
		}
	}

	
	/**   
	 * @Title: setHeader   
	 * @Description: TODO 设置首页的背景大图  
	 * @param: @param header_imgPath 图片路径
	 * @return: void      
	 * @throws   
	 */
	public void setHeader(String header_imgPath) {
		// 活动窗格
		Dispatch activePane = Dispatch.get(activeWindow, "ActivePane").toDispatch();
		// 视窗对象
		Dispatch view = Dispatch.get(activePane, "View").toDispatch();
		// 打开页眉，值为9，页脚值为10
		Dispatch.put(view, "SeekView", new Variant(9));
		// 获取页眉和页脚
		Dispatch headerfooter = Dispatch.get(selection, "HeaderFooter").toDispatch();
		// 获取水印图形对象
		Dispatch shapes = Dispatch.get(headerfooter, "Shapes").toDispatch();
		// 调用shapes对象的AddPicture方法将全路径为picname的图片插入当前文档
		Dispatch picture = Dispatch.call(shapes, "AddPicture", header_imgPath).toDispatch();
		Dispatch.call(picture, "Select");
		//设置图片的位置和大小
		Dispatch.put(picture, "Left", new Variant(423));
		Dispatch.put(picture, "Top", new Variant(-30));
		Dispatch.put(picture, "Width", new Variant(80));
		Dispatch.put(picture, "Height", new Variant(50));
		// 0表示恢复视图;
		Dispatch.put(view, "SeekView", new Variant(0)); 
		logger1.info("*****设置页眉图片*****");
	}

	/**   
	 * @Title: setPageNum   
	 * @Description: TODO 插入页码作为页脚  
	 * @param:       
	 * @return: void      
	 * @throws   
	 */
	public void setPageNum() {
		// 活动窗格
		Dispatch activePane = Dispatch.get(activeWindow, "ActivePane").toDispatch();
		// 视窗对象
		Dispatch view = Dispatch.get(activePane, "View").toDispatch();
		// 打开页眉，值为9，页脚值为10
		Dispatch.put(view, "SeekView", new Variant(10));
		final Dispatch Sections = Dispatch.get(document, "Sections").toDispatch();
		final Dispatch item = Dispatch.call(Sections, "Item", new Variant(1)).toDispatch();
		final Dispatch footer = Dispatch.get(item, "Footers").toDispatch();
		final Dispatch f1 = Dispatch.call(footer, "Item", new Variant(1)).toDispatch();
		final Dispatch range = Dispatch.get(f1, "Range").toDispatch();
		final Dispatch fields = Dispatch.get(range, "Fields").toDispatch();
		Dispatch paragraphFormat = (Dispatch) Dispatch.get(selection, "ParagraphFormat").getDispatch();
		Dispatch.put(paragraphFormat, "Alignment", 2);
		Dispatch.call(fields, "Add", Dispatch.get(selection, "Range").toDispatch(), new Variant(-1), "Page", true)
				.toDispatch();
		Dispatch.call(selection, "TypeText", "/");
		Dispatch.call(fields, "Add", Dispatch.get(selection, "Range").toDispatch(), new Variant(-1), "NumPages", true)
				.toDispatch();
		Dispatch font = Dispatch.get(range, "Font").toDispatch();
		Dispatch.put(font, "Name", new Variant("宋体_GB2312"));
		Dispatch.put(font, "Size", 9);
		// 0表示恢复视图;
		Dispatch.put(view, "SeekView", new Variant(0)); 
		logger1.info("*****设置页脚页码*****");
	}

	/**   
	 * @Title: setFooter   
	 * @Description: TODO 设置页面右边的声明文字 
	 * @param: @param headerStr      
	 * @return: void      
	 * @throws   
	 */
	public void setFooter(String headerStr) {
		// 活动窗格
		Dispatch activePane = Dispatch.get(activeWindow, "ActivePane").toDispatch();
		// 视窗对象
		Dispatch view = Dispatch.get(activePane, "View").toDispatch();
		// 打开页眉，值为9，页脚值为10
		Dispatch.put(view, "SeekView", new Variant(10));
		final Dispatch Sections = Dispatch.get(document, "Sections").toDispatch();
		final Dispatch item = Dispatch.call(Sections, "Item", new Variant(1)).toDispatch();
		final Dispatch footer = Dispatch.get(item, "Footers").toDispatch();
		final Dispatch f1 = Dispatch.call(footer, "Item", new Variant(1)).toDispatch();
		final Dispatch range = Dispatch.get(f1, "Range").toDispatch();
		Dispatch paragraphFormat = (Dispatch) Dispatch.get(selection, "ParagraphFormat").getDispatch();
		Dispatch.put(paragraphFormat, "Alignment", 2);
		Dispatch.call(selection, "TypeText", headerStr);
		Dispatch font = Dispatch.get(range, "Font").toDispatch();
		Dispatch.put(font, "Name", new Variant("宋体_GB2312"));
		Dispatch.put(font, "Size", 9);
		// 0表示恢复视图;
		Dispatch.put(view, "SeekView", new Variant(0)); 
		logger1.info("*****设置页脚文字*****");
	}

	/**
	 * 对当前段落进行格式化
	 * 
	 * @param lineSpacing
	 *            设置排列方式 默认：4:固定值大小
	 * @param lineSpace
	 *            设置行间距 默认：1.0 0：1.0 1：1.5 2：2.0 3：最小值 4：固定值
	 */
	public void setParaFormat(int lineSpace, int lineSpacing) {
		Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();
		Dispatch.put(alignment, "LineSpacingRule", new Variant(lineSpace));
		Dispatch.put(alignment, "LineSpacing", new Variant(lineSpacing));
		logger1.info("*****设置行间距*****");
	}

	public void select(Dispatch dispatch) {
		Dispatch.call(dispatch, "Select");
	}

	/**
	 * 合并表格
	 * 
	 * @param selection
	 *            操作对象
	 * @param tableIndex
	 *            表格起始点
	 * @param fstCellRowIdx
	 *            开始行
	 * @param fstCellColIdx
	 *            开始列
	 * @param secCellRowIdx
	 *            结束行
	 * @param secCellColIdx
	 *            结束列
	 */
	public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx, int

	secCellRowIdx, int secCellColIdx) {

		logger1.info("*****合并单元格*****");
		if (this.table == null) {
			logger1.info("*****table对象为空*****");
			return;
		}
		Dispatch fstCell = Dispatch.call(table, "Cell", new Variant(fstCellRowIdx), new Variant

		(fstCellColIdx)).toDispatch();
		Dispatch secCell = Dispatch.call(table, "Cell", new Variant(secCellRowIdx), new Variant

		(secCellColIdx)).toDispatch();
		Dispatch.call(fstCell, "Merge", secCell);
	}

	/**
	 * 想Table对象中插入数值
	 * <p>
	 * 参数形式：ArrayList<String[]>List.size()为表格的总行数<br>
	 * String[]的length属性值应该与所创建的表格列数相同
	 * 
	 * @param selection
	 *            插入点
	 * @param tableIndex
	 *            表格起始点
	 * @param list
	 *            数据内容
	 */
	public void insertToTable(List<String[]> list) {

		logger1.info("向Table对象中插入数据...");
		logger1.info("向Table对象中插入数据...");
		if (list == null || list.size() <= 0) {
			logger1.info("写出数据集为空...");
			return;
		}
		if (this.table == null) {
			logger1.info("table对象为空...");
			return;
		}
		for (int i = 0; i < list.size(); i++) {
			String[] strs = list.get(i);
			for (int j = 0; j < strs.length; j++) {
				/* 遍历表格中每一个单元格，遍历次数与所要填入的内容数量相同 */
				Dispatch cell = this.getCell(i + 1, j + 1);
				/* 选中此单元格 */
				Dispatch.call(cell, "Select");
				/* 写出内容到此单元格中 */
				Dispatch.put(this.selection, "Text", strs[j]);
				/* 移动游标到下一个位置 */
			}
			this.moveDown(1);
		}
		this.enterDown(1);
	}

	/**
	 * 设置当前表格指定行的行高
	 * 
	 * @param rowHeight
	 * @param rowIndex
	 */
	public void setRowHeight(float rowHeight, int rowIndex) {
		if (rowHeight > 0) {
			if (rows == null || row == null) {
				this.getTableRows();
				this.getTableRow(rowIndex);
			}
			Dispatch.put(row, "Height", new Variant(rowHeight));
		}
	}

	/**
	 * 在文档中正常插入文字内容
	 * 
	 * @param selection
	 *            插入点
	 * @param list
	 *            数据内容
	 */
	public void insertToDocument(List<String> list) {

		logger1.info("向Document对象中插入数据...");
		if (list == null || list.size() <= 0) {
			logger1.info("写出数据集为空...");
			return;
		}
		if (this.document == null) {
			logger1.info("document对象为空...");
			return;
		}
		for (String str : list) {
			/* 写出至word中 */
			this.applyListTemplate(3, 2);
			Dispatch.put(this.selection, "Text", str);
			this.moveDown(1);
			this.enterDown(1);
		}
	}

	/**
	 * 创建新的表格
	 * 
	 * @param selection
	 *            插入点
	 * @param document
	 *            文档对象
	 * @param rowCount
	 *            行数
	 * @param colCount
	 *            列数
	 * @param width
	 *            边框数值 0浅色1深色
	 * @return 新创建的表格对象
	 */
	public Dispatch createNewTable(int rowCount, int colCount, int width) {

		logger1.info("创建新的表格...");
		if (this.tables == null) {
			this.getTables();
		}
		this.getRange();
		if (rowCount > 0 && colCount > 0) {
			this.table = Dispatch.call(this.tables, "Add", this.range, new Variant(rowCount), new

			Variant(colCount), new Variant(width)).toDispatch();
		}
		/* 返回新创建表格 */
		return this.table;
	}

	/**
	 * 获取Document对象中的所有Table对象
	 * 
	 * @return 所有Table对象
	 */
	public Dispatch getTables() {

		logger1.info("*****获取所有表格对象*****");
		if (this.document == null) {
			logger1.info("document对象为空...");
			return this.tables;
		}
		this.tables = Dispatch.get(this.document, "Tables").toDispatch();
		return this.tables;

	}

	/**
	 * 获取Document中Table的数量
	 * 
	 * @return 表格数量
	 */
	public int getTablesCount() {

		logger1.info("*****获取文档中表格数量*****");
		if (this.tables == null) {
			this.getTables();
		}
		return Dispatch.get(tables, "Count").getInt();

	}

	/**
	 * 获取指定序号的Table对象
	 * 
	 * @param tableIndex
	 *            Table序列
	 * @return
	 */
	public Dispatch getTable(int tableIndex) {

		logger1.info("*****获取指定表格对象*****");
		if (this.tables == null) {
			this.getTables();
		}
		if (tableIndex >= 0) {
			this.table = Dispatch.call(this.tables, "Item", new Variant(tableIndex)).toDispatch();

		}

		return this.table;
	}

	/**
	 * 获取表格的总列数
	 * 
	 * @return 总列数
	 */
	public int getTableColumnsCount() {

		logger1.info("获取表格总行数...");
		if (this.table == null) {
			logger1.info("table对象为空...");
			return 0;
		}
		return Dispatch.get(this.cols, "Count").getInt();
	}

	/**
	 * 获取表格的总行数
	 * 
	 * @return 总行数
	 */
	public int getTableRowsCount() {

		logger1.info("获取表格总行数...");
		if (this.table == null) {
			logger1.info("table对象为空...");
			return 0;
		}
		return Dispatch.get(this.rows, "Count").getInt();
	}

	/**
	 * 获取表格列对象
	 * 
	 * @return 列对象
	 */
	public Dispatch getTableColumns() {

		logger1.info("获取表格行对象...");
		if (this.table == null) {
			logger1.info("table对象为空...");
			return this.cols;
		}
		this.cols = Dispatch.get(this.table, "Columns").toDispatch();
		return this.cols;
	}

	/**
	 * 获取表格的行对象
	 * 
	 * @return 总行数
	 */
	public Dispatch getTableRows() {

		logger1.info("获取表格总行数...");
		if (this.table == null) {
			logger1.info("table对象为空...");
			return this.rows;
		}
		this.rows = Dispatch.get(this.table, "Rows").toDispatch();
		return this.rows;
	}

	/**
	 * 获取指定表格列对象
	 * 
	 * @return 列对象
	 */
	public Dispatch getTableColumn(int columnIndex) {

		logger1.info("获取指定表格行对象...");
		if (this.cols == null) {
			this.getTableColumns();
		}
		if (columnIndex >= 0) {
			this.col = Dispatch.call(this.cols, "Item", new Variant(columnIndex)).toDispatch();
		}
		return this.col;
	}

	/**
	 * 获取表格中指定的行对象
	 * 
	 * @param rowIndex
	 *            行序号
	 * @return 行对象
	 */
	public Dispatch getTableRow(int rowIndex) {

		logger1.info("获取指定表格总行数...");
		if (this.rows == null) {
			this.getTableRows();
		}
		if (rowIndex >= 0) {
			this.row = Dispatch.call(this.rows, "Item", new Variant(rowIndex)).toDispatch();
		}
		return this.row;
	}

	/**
	 * 设置当前表格的所有列的列宽
	 * 
	 * @param columnWidth
	 *            列宽 取值范围：10<columnWidth 默认值：120
	 */
	public void setColumnWidth(float columnWidth) {
		if (columnWidth < 11) {
			columnWidth = 120;
		}
		if (cols == null)
			this.getTableColumns();
		Dispatch.put(cols, "Width", new Variant(columnWidth));
	}

	/**
	 * 自动调整表格
	 */
	public void autoFitTable() {
		Dispatch tables = this.getTables();
		logger1.info("*****自动调整表格*****");
		int count = this.getTablesCount();
		logger1.info("*****共有" + count + "个表格*****");
		for (int i = 0; i < count; i++) {
			Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1)).toDispatch();
			Dispatch.call(table, "AutoFitBehavior", new Variant(2));
		}
	}

	/**   
	 * @Title: setApplyTableFormat   
	 * @Description: TODO 设置表格根据窗口大小自动调整 
	 * @param:       
	 * @return: void      
	 * @throws   
	 */
	public void setApplyTableFormat() {
		Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
		int tabCount = Integer.valueOf(Dispatch.get(tables, "Count").toString());
		for (int i = 1; i <= tabCount; i++) {
			Dispatch table = Dispatch.call(tables, "Item", new Variant(i)).toDispatch();
			Dispatch.call(table, "AutoFitBehavior", new Variant(2));// 设置自动调整表格方式,1-根据窗口自动调整
		}
		logger1.info("*****根据窗口自动调整表格*****");
	}

	/**
	 * 获取当前文档中，表格中的指定单元格
	 * 
	 * @param CellRowIdx
	 *            单元格所在行
	 * @param CellColIdx
	 *            单元格所在列
	 * @return 指定单元格对象
	 */
	public Dispatch getCell(int cellRowIdx, int cellColIdx) {

		logger1.info("*****获取当前文档中，表格中的指定单元格*****");
		if (this.table == null) {
			logger1.info("table对象为空...");
			return this.cell;
		}
		if (cellRowIdx >= 0 && cellColIdx >= 0) {
			this.cell = Dispatch.call(this.table, "Cell", new Variant(cellRowIdx), new Variant

			(cellColIdx)).toDispatch();
		}
		return this.cell;
	}

	/**   
	 * @Title: getCellText   
	 * @Description: TODO 获取当前文档中表格的指定单元格内容  
	 * @param: @param cellRowIdx
	 * @param: @param cellColIdx
	 * @param: @return      
	 * @return: String      
	 * @throws   
	 */
	public String getCellText(int cellRowIdx, int cellColIdx) {

		logger1.info("*****获取当前文档中，表格中的指定单元格内容*****");
		if (this.table == null) {
			logger1.info("table对象为空...");
			return null;
		}
		if (cellRowIdx >= 0 && cellColIdx >= 0) {
			this.cell = Dispatch.call(this.table, "Cell", new Variant(cellRowIdx), new Variant

			(cellColIdx)).toDispatch();
		}
		Dispatch range = Dispatch.get(cell, "Range").toDispatch();
		String data = Dispatch.get(range, "Text").getString();
		return data;
	}

	/**   
	 * @Title: setCell   
	 * @Description: TODO 设置当前文档中表格中指定单元格的值 
	 * @param: @param cellRowIdx
	 * @param: @param cellColIdx
	 * @param: @param words      
	 * @return: void      
	 * @throws   
	 */
	public void setCell(int cellRowIdx, int cellColIdx,String words) {

		logger1.info("*****获取当前文档中，表格中的指定单元格*****");
		if (this.table == null) {
			logger1.info("table对象为空...");
		}
		if (cellRowIdx >= 0 && cellColIdx >= 0) {
			this.cell = Dispatch.call(this.table, "Cell", new Variant(cellRowIdx), new Variant

			(cellColIdx)).toDispatch();
			Dispatch.call(getCell(cellRowIdx, cellColIdx), "Select");
			Dispatch.put(this.selection, "Text", words);
		}
	}

	/**
	 * 设置文档标题
	 * 
	 * @param title
	 *            标题内容
	 */
	public void setTitle(String title) {

		logger1.info("设置文档标题...");
		if (title == null || "".equals(title)) {
			logger1.info("文档标题为空...");
			return;
		}
		Dispatch.call(this.selection, "TypeText", title);
	}

	/**
	 * 设置当前表格线的粗细
	 * 
	 * @param width
	 *            width范围：1<w<13,如果是0，就代表没有框
	 */
	public void setTableBorderWidth(int width) {

		logger1.info("设置当前表格线的粗细...");
		if (this.table == null) {
			logger1.info("table对象为空...");
			return;
		}
		/*
		 * 设置表格线的粗细 1：代表最上边一条线 2：代表最左边一条线 3：最下边一条线 4
		 * 
		 * ：最右边一条线 5：除最上边最下边之外的所有横线 6：除最左边最右边之外的所有竖线 7：从左上角到右下角的斜线 8：从左下角到右上
		 * 
		 * 角的斜线
		 */
		Dispatch borders = Dispatch.get(table, "Borders").toDispatch();
		Dispatch border = null;
		for (int i = 1; i < 7; i++) {
			border = Dispatch.call(borders, "Item", new Variant(i)).toDispatch();
			if (width != 0) {
				Dispatch.put(border, "LineWidth", new Variant(width));
				Dispatch.put(border, "Visible", new Variant(true));
			} else if (width == 0) {
				Dispatch.put(border, "Visible", new Variant(false));
			}
		}
	}

	/**
	 * 对当前selection设置项目符号和编号
	 * 
	 * @param tabIndex
	 *            1: 项目编号 2: 编号 3: 多级编号 4: 列表样式
	 * @param index
	 *            0:表示没有 ,其它数字代表的是该Tab页中的第几项内容
	 */
	public void applyListTemplate(int tabIndex, int index) {

		logger1.info("对当前selection设置项目符号和编号...");
		/* 取得ListGalleries对象列表 */
		Dispatch listGalleries = Dispatch.get(this.word, "ListGalleries").toDispatch();
		/* 取得列表中一个对象 */
		Dispatch listGallery = Dispatch.call(listGalleries, "Item", new Variant

		(tabIndex)).toDispatch();
		Dispatch listTemplates = Dispatch.get(listGallery, "ListTemplates").toDispatch();
		if (this.range == null) {
			this.getRange();
		}
		Dispatch listFormat = Dispatch.get(this.range, "ListFormat").toDispatch();
		Dispatch.call(listFormat, "ApplyListTemplate", Dispatch.call(listTemplates, "Item", new

		Variant(index)), new Variant(true), new Variant(1), new Variant(0));
	}

	/**
	 * 增加文档目录
	 * 
	 * 目前采用固定参数方式，以后可以动态进行调整
	 */
	public void addTablesOfContents() {
		/* 取得ActiveDocument、TablesOfContents、range对象 */
		Dispatch ActiveDocument = word.getProperty("ActiveDocument").toDispatch();
		Dispatch TablesOfContents = Dispatch.get

		(ActiveDocument, "TablesOfContents").toDispatch();
		Dispatch range = Dispatch.get(this.selection, "Range").toDispatch();
		/* 增加目录 */
		Dispatch.call(TablesOfContents, "Add", range, new Variant(true), new Variant(1), new

		Variant(3), new Variant(true), new Variant(""), new Variant(true), new Variant(true));

	}

	/**
	 * 设置当前Selection 位置方式
	 * 
	 * @param selectedContent
	 *            0－居左；1－居中；2－居右。
	 */
	public void setAlignment(int alignmentType) {

		logger1.info("设置当前Selection 位置方式...");
		if (this.alignment == null) {
			this.getAlignment();
		}
		Dispatch.put(this.alignment, "Alignment", alignmentType);
	}

	/**
	 * 获取当前选择区域的对齐方式
	 * 
	 * @return 对其方式对象
	 */
	public Dispatch getAlignment() {

		logger1.info("*****获取当前选择区域的对齐方式*****");
		if (this.selection == null) {
			this.getSelection();
		}
		this.alignment = Dispatch.get(this.selection, "ParagraphFormat").toDispatch();
		return this.alignment;
	}

	/**
	 * 获取字体对象
	 * 
	 * @return 字体对象
	 */
	public Dispatch getFont() {

		logger1.info("*****获取字体对象*****");
		if (this.selection == null) {
			this.getSelection();
		}
		this.font = Dispatch.get(this.selection, "Font").toDispatch();
		return this.font;
	}

	/**
	 * 设置选定内容的字体 注：在调用此方法前，选定区域对象selection必须存在
	 * 
	 * @param fontName
	 *            字体名称，例如 "宋体"
	 * @param isBold
	 *            粗体
	 * @param isItalic
	 *            斜体
	 * @param isUnderline
	 *            下划线
	 * @param rgbColor
	 *            颜色，例如"255,255,255"
	 * @param fontSize
	 *            字体大小
	 * @param Scale
	 *            字符间距，百分比值。例如 70代表缩放为70%
	 */
	public void setFontScale(String fontName, boolean isBold, boolean isItalic, boolean

	isUnderline, String rgbColor, int Scale, int fontSize) {

		logger1.info("设置字体...");
		Dispatch.put(this.font, "Name", fontName);
		Dispatch.put(this.font, "Bold", isBold);
		Dispatch.put(this.font, "Italic", isItalic);
		Dispatch.put(this.font, "Underline", isUnderline);
		Dispatch.put(this.font, "Color", rgbColor);
		Dispatch.put(this.font, "Scaling", Scale);
		Dispatch.put(this.font, "Size", fontSize);
	}

	/**
	 * 保存文件
	 * 
	 * @param outputPath
	 *            输出文件（包含路径）
	 */
	public void saveAs(String outputPath) {

		logger1.info("*****保存文件*****");
		if (this.document == null) {
			logger1.info("*****document对象为空*****");
			return;
		}
		if (outputPath == null || "".equals(outputPath)) {
			logger1.info("*****文件保存路径为空*****");
			return;
		}
		Dispatch.call(this.document, "SaveAs", outputPath);
	}

	public void saveAsHtml(String htmlFile) {
		Dispatch.invoke(this.document, "SaveAs", Dispatch.Method, new Object[] { htmlFile, new

				Variant(8) }, new int[1]);
	}

	/**
	 * 关闭文件
	 * 
	 * @param document
	 *            要关闭的文件
	 */
	public void close() {

		logger1.info("*****关闭文件*****");
		if (document == null) {
			logger1.info("*****document对象为空*****");
			return;
		}
		Dispatch.call(document, "Close", new Variant(0));
	}

	/**
	 * 列印word文件
	 * 
	 */
	public void printFile() {
		logger1.info("打印文件...");
		if (document == null) {
			logger1.info("document对象为空...");
			return;
		}
		Dispatch.call(document, "PrintOut");
	}

	/**
	 * 退出程序
	 */
	public void quit() {

		logger1.info("*****退出程序*****");
		word.invoke("Quit", new Variant[0]);
		ComThread.Release();
	}
}